package com.zcc.gaoji;

//测试：生产者消费者模型——>利用缓冲区解决：管程法

//生产者，消费者，产品，缓冲区
public class TestPC {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        new Thread(new Producer(synContainer)).start();
        new Thread(new Consumer(synContainer)).start();
    }
}

//生产者
class Producer implements Runnable{
    SynContainer synContainer;
    public Producer(SynContainer synContainer){
        this.synContainer = synContainer;
    }
    @Override
    public void run() {
        //生产者生产
        for (int i = 0; i < 100; i++) {
            synContainer.push(new Chiken(i));
            System.out.println("生产了"+i+"只鸡");
        }
    }
}

//消费者
class Consumer implements Runnable{
    SynContainer synContainer;
    public Consumer(SynContainer synContainer){
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费者消费了"+synContainer.pop().id+"只鸡");

        }
    }
}

//产品
class Chiken{
    int id;
    public Chiken(int id){
        this.id = id;
    }
}

//缓冲区
class SynContainer{
    //需要一个容器大小，最多存放量
    Chiken[] chikens = new Chiken[10];
    //容器计数器
    int count = 0;
    //生产者放入产品
    public synchronized void push(Chiken chiken){
        //如果容器满了，就需要等待消费者消费
        if(count==chikens.length){
            //通知消费者消费，生产者等待
            try{
                this.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        //如果没有满，需要丢入产品
        chikens[count++] = chiken;
        //可以通知消费者消费了
        this.notifyAll();
    }
    //消费者消费产品
    public synchronized Chiken pop(){
        //判断能否消费
        if(count==0){
            //等待生产者生成
            try {
                this.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        //如果可以消费
        count--;
        Chiken chiken = chikens[count];
        //消费结束，通知生产者生产
        this.notifyAll();
        return chiken;
    }
}

